package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import db.Dbclose;
import db.Dbconn;
import entity4wms.Deliver;
import tools.ResultSetPrinter;

public final class DAOdeliver {
    static Connection conn = null;
    static PreparedStatement pstmt = null;
    static ResultSet rs = null;

    public static Deliver addDeliver(Deliver deliver) throws SQLException, ClassNotFoundException {
        String sql = "insert into entry(gid,uid,edate,enumber) values(?,?,CURRENT_TIME(),?)";
        conn = Dbconn.getConnection();
        pstmt = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
        pstmt.setInt(1, deliver.getGid());
        pstmt.setInt(2, deliver.getUid());
        pstmt.setInt(3, deliver.getNumber());
        pstmt.executeUpdate();
        rs = pstmt.executeQuery("select * from deliver");
        rs.absolute(-1);
        deliver.setId(rs.getInt(1));
        Dbclose.close(pstmt, conn);
        return deliver;
    
    }


    public static void removeDeliver(Deliver deliver) throws SQLException, ClassNotFoundException{
        String sql = "delete from deliver where did=?";
        conn = Dbconn.getConnection();
        pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, deliver.getId());

        pstmt.executeUpdate();
        Dbclose.close(pstmt, conn);
    }

    public static void updateDeliver(Deliver deliver) throws SQLException, ClassNotFoundException{
        String sql = "update deliver set gid =?,uid =?,ddate = NOW(),dnum =? where did=?";
        conn = Dbconn.getConnection();
        pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, deliver.getGid());
        pstmt.setInt(2, deliver.getUid());
        pstmt.setInt(3, deliver.getNumber());
        pstmt.setInt(4, deliver.getId());
        pstmt.executeUpdate();
        Dbclose.close(pstmt, conn);
    }

    public static void queryDeliver(Deliver deliver) throws SQLException, ClassNotFoundException{
        String sql1 = "select did,gname,uname,ddate,dnum from goods,uaccount,deliver where deliver.gid=goods.gid and  deliver.uid=uaccount.uid";

        conn = Dbconn.getConnection();
        pstmt = conn.prepareStatement(sql1);
            
        // pstmt.setInt(2, entry.getUid());
        // pstmt.setDate(3, entry.getEdate());
        // pstmt.setInt(4, entry.getEnumber());
        rs = pstmt.executeQuery();
        
        ResultSetPrinter.printResultSet(rs);

        Dbclose.queryClose(pstmt, rs, conn);
    }
}